import {
	HttpErrorResponse,
	HttpEvent,
	HttpHandler,
	HttpInterceptor,
	HttpRequest,
	HttpResponseBase
} from '@angular/common/http';
import { Injectable, Injector } from '@angular/core';

import { environment } from '@env/environment';


import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable, catchError, mergeMap, of, throwError } from 'rxjs';

/**
 * 默认HTTP拦截器
 */
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
	constructor(
		private injector: Injector
	) { }

	private get notification(): NzNotificationService {
		return this.injector.get(NzNotificationService);
	}

	private handleError(ev: HttpErrorResponse): void {
		console.log(ev);
		//this.notification.error(`请求错误 `, ev);
	}

	private handleData(ev: HttpResponseBase): Observable<NzSafeAny> {
		// 业务处理：一些通用操作
		return of(ev);
	}

	intercept(req: HttpRequest<NzSafeAny>, next: HttpHandler): Observable<HttpEvent<NzSafeAny>> {
		// 统一加上服务端前缀
		let url = req.url;
		if (!url.startsWith('https://') && !url.startsWith('http://')) {
			const { baseUrl } = environment.api;
			url = baseUrl + (baseUrl.endsWith('/') && url.startsWith('/') ? url.substring(1) : url);
		}

		const newReq = req.clone({ url });
		return next.handle(newReq).pipe(
			mergeMap(ev => {
				// 允许统一对请求错误处理
				if (ev instanceof HttpResponseBase) {
					return this.handleData(ev);
				}
				// 若一切都正常，则后续操作
				return of(ev);
			}),
			catchError((err: HttpErrorResponse) => {
				this.handleError(err);
				return throwError(() => err);
			})
		);
	}
}
